//
//  BDPostViewController.m
//  BadBoy
//
//  Created by wen on 2017/9/1.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPostListViewController.h"
#import "BDPostCell.h"
#import "BDUserModel.h"
#import "BDCityInfo.h"
#import "BDPhotoGroupView.h"
#import "BDUserInfoViewController.h"
#import "PopoverView.h"
#import "BDTextFieldAlert.h"
//#import "BDFridentInfo.h"
#import "BDFMDBTool.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "BDPostDetailViewController.h"

@interface BDPostListViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, BDPostCellDelegate>
{
    NSMutableArray *syncCellArray;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDPostListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.datasource = [NSMutableArray array];
    syncCellArray = [NSMutableArray array];
    [self requestDatasource];
}

- (void)requestDatasource{
    for (NSDictionary *dic in _data) {
        BDPostModel *post = [BDPostModel modelWithDictionary:dic];
        BDPostLayout *layout = [[BDPostLayout alloc] initWithPost:post];
        [_datasource addObject:layout];
    }
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"postCell";
    BDPostCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.delegate = self;
    BDPostLayout *layout = _datasource[indexPath.row];
    layout.isDetail = NO;
    [cell setLayout:layout needCoverText:YES];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ((BDPostLayout *)_datasource[indexPath.row]).height;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight - kBDTabBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.contentInset = UIEdgeInsetsMake(self.topView.height, 0, 0, 0);
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 10;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.1)];
        [_tableView registerClass:[BDPostCell class] forCellReuseIdentifier:@"postCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _tableView) {
        for (BDPostCell *cell in syncCellArray) {
            [cell.postView setDisplayAsync:YES];
        }
        [syncCellArray removeAllObjects];
    }
}

///点击了cell
- (void)cellDidClick:(BDPostCell *)cell {
    BDPostDetailViewController *detailVC = [[BDPostDetailViewController alloc] init];
    detailVC.postId = cell.postView.layout.post.my_id;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

///点击了全文
- (void)cellDidClickOpen:(BDPostCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    BDPostLayout *layout = _datasource[indexPath.row];
    layout.isOpen = !layout.isOpen;
    [layout calculateHeight];
    if (cell.postView.displayAsync == YES) {
        [cell.postView setDisplayAsync:NO];
        [syncCellArray addObject:cell];
    }
    
    [cell setLayout:layout needCoverText:NO];
    
    [UIView performWithoutAnimation:^{
        [_tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
    }];
}

/// 点击了用户
- (void)cell:(BDPostCell *)cell didClickUser:(BDUserModel *)user {
    BDPostModel *post = cell.postView.layout.post;
    BDUserInfoViewController *infoVC = [[BDUserInfoViewController alloc] initWithUserID:post.user.user_id isFollow:post.is_follow guanzhuBlock:^(BOOL isFollow) {
        post.is_follow = isFollow;
    }];
    [self.navigationController pushViewController:infoVC animated:YES];
}

//点击图片
- (void)cell:(BDPostCell *)cell didClickImageAtIndex:(NSUInteger)index {
    UIView *fromView = nil;
    NSMutableArray *items = [NSMutableArray new];
    BDPostModel *post = cell.postView.layout.post;
    NSArray *pics = post.repost ? post.repost.images : post.images;
    
    for (NSUInteger i = 0, max = pics.count; i < max; i++) {
        UIView *imgView = cell.postView.picViews[i];
//        WBPicture *pic = pics[i];
//        WBPictureMetadata *meta = pic.largest.badgeType == WBPictureBadgeTypeGIF ? pic.largest : pic.large;
        BDPhotoGroupItem *item = [BDPhotoGroupItem new];
        item.thumbView = imgView;
//        item.largeImageURL = meta.url;
//        item.largeImageSize = CGSizeMake(meta.width, meta.height);
        [items addObject:item];
        if (i == index) {
            fromView = imgView;
        }
    }
    
    BDPhotoGroupView *v = [[BDPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:[UIApplication sharedApplication].keyWindow animated:YES completion:nil];
}

///点赞
- (void)cellDidClickLike:(BDPostCell *)cell {
    BDPostModel *post = cell.postView.layout.post;
    [cell.postView.toolbarView setLiked:!post.praise withAnimation:post.praise == NO];
    
    NSString *url = [NSString stringWithFormat:@"%@post/%@/praise", KBDBaseURL, @(post.my_id)];
    NSDictionary *para = @{@"id":@(post.my_id)};
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [cell.postView.toolbarView setLiked:!post.praise withAnimation:NO];
    }];
}

///评论
- (void)cellDidClickComment:(BDPostCell *)cell{
    BDPostModel *post = cell.postView.layout.post;
    //这里分情况，如果当前评论数为0，则直接跳转到评论页面，否则进入详情页然后再可以跳转到评论页面
    if (post.commentCount == 0) {
//        BDHomeDetailViewController *commntVC = [[BDHomeDetailViewController alloc] init];
//        commntVC.homeModel = post;
//        commntVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:commntVC animated:YES];
    }else{
        BDPostDetailViewController *detailVC = [[BDPostDetailViewController alloc] init];
        detailVC.postId = cell.postView.layout.post.my_id;
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

///分享
- (void)cellDidClickShared:(BDPostCell *)cell {
    BDPostModel *post = cell.postView.layout.post;
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine),@(UMSocialPlatformType_WechatFavorite)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        NSString *url = [NSString stringWithFormat:@"%@tool/shareData", KBDBaseURL];
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        
        [signal subscribeNext:^(id  _Nullable x) {
            //创建分享消息对象
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            
            //创建网页内容对象
            NSString *thumbURL = x[@"share_logo"];
            NSString *title = x[@"share_title"];
            NSString *descr = x[@"share_text"];
            NSString *webUrl = x[@"share_url"];
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title
                                                                                     descr:descr
                                                                                 thumImage:thumbURL];
            //设置网页地址
            shareObject.webpageUrl = webUrl;
            
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                if (error) {
//                    UMSocialLogInfo(@"************Share fail with error %@*********",error);
                }else{
                    if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                        NSString *backUrl = [NSString stringWithFormat:@"%@post/%@/shared", KBDBaseURL, @(post.my_id)];
                        RACSignal *backSignal = [[BDNetworkingServer yy_POST:backUrl parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                        [backSignal subscribeNext:^(id  _Nullable x) {
                            post.sharedCount++;
                            [self.tableView reloadData];
                            [MBManager showBriefAlert:ASLocalizedString(@"分享成功")clickHidden:NO clickBlock:nil];
                        }];
                        [backSignal subscribeError:^(NSError * _Nullable error) {
                            [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                        }];
                    }else{
                        //                            UMSocialLogInfo(@"response data is %@",data);
                        [MBManager showBriefAlert:ASLocalizedString(@"分享失败")clickHidden:NO clickBlock:nil];
                    }
                }
            }];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager showBriefAlert:ASLocalizedString(@"获取分享信息失败")clickHidden:NO clickBlock:nil];
        }];
    }];
}

- (void)cellDidClickMenu:(BDPostCell *)cell {
    BDPostModel *post = cell.postView.layout.post;
    PopoverAction *addFriAction = [PopoverAction actionWithTitle:ASLocalizedString(@"加好友")handler:^(PopoverAction *action) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            [BDTextFieldAlert showWithTitle:ASLocalizedString(@"添加好友")placeHolder:ASLocalizedString(@"打个招呼吧")finishBlock:^(NSString *text) {
                NSInteger userId = post.user.user_id;
//                EMError *error = [[EMClient sharedClient].contactManager addContact:[NSString stringWithFormat:@"%@", @(userId)] message:text];
//                if (!error) {
//                    [MBManager showBriefAlert:ASLocalizedString(@"请求已发送")clickHidden:NO clickBlock:nil];
//                }
            }];
        }];
    }];
    NSString *guanzhuTitle = post.is_follow == YES ? ASLocalizedString(@"取消关注"): ASLocalizedString(@"关注");
    PopoverAction *QRAction = [PopoverAction actionWithTitle:guanzhuTitle handler:^(PopoverAction *action) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            NSInteger guanzhuUserId = post.user.user_id;
            NSString *url = [NSString stringWithFormat:@"%@follow/%@", KBDBaseURL, @(guanzhuUserId)];
            NSString *headValid = [BDUserModel getHeaderValidation];
            //        NSDictionary *para = @{@"id":@(self.model.my_id)};
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
            [signal subscribeNext:^(id  _Nullable x) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), guanzhuTitle] clickHidden:NO clickBlock:nil];
                post.is_follow = [x[@"status"] boolValue];
                //发送给首页的，当关注人变更之后，首页关注列表也要跟着变更
                [[NSNotificationCenter defaultCenter] postNotificationName:@"guanzhuChange" object:nil];
            }];
            
            [signal subscribeError:^(NSError * _Nullable error) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), guanzhuTitle] clickHidden:NO clickBlock:nil];
                // BDLog(ASLocalizedString(@"关注操作失败：%@"), error);
            }];
        }];
    }];
    NSString *shoucangTitle = post.fav == YES ? ASLocalizedString(@"取消收藏"): ASLocalizedString(@"收藏");
    PopoverAction *facetofaceAction = [PopoverAction actionWithTitle:shoucangTitle handler:^(PopoverAction *action) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            NSString *url = [NSString stringWithFormat:@"%@post/%@/fav", KBDBaseURL, @(post.my_id)];
            NSString *headValid = [BDUserModel getHeaderValidation];
            NSDictionary *para = @{@"id":@(post.my_id)};
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
            [signal subscribeNext:^(id  _Nullable x) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), shoucangTitle] clickHidden:NO clickBlock:nil];
                post.fav = [x[@"status"] boolValue];
            }];
            
            [signal subscribeError:^(NSError * _Nullable error) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), shoucangTitle] clickHidden:NO clickBlock:nil];
                // BDLog(ASLocalizedString(@"收藏失败：%@"), error);
            }];
        }];
    }];
    
    PopoverAction *blackListAction = [PopoverAction actionWithTitle:ASLocalizedString(@"加入黑名单")handler:^(PopoverAction *action) {
        [BDUserModel judgeCurrentUserWithNormalBlock:^{
            NSString *url = [NSString stringWithFormat:@"%@blackList/%@", KBDBaseURL, @(post.user.user_id)];
            NSString *headValid = [BDUserModel getHeaderValidation];
            NSDictionary *para = @{@"id":@(post.user.user_id)};
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
            RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
            [signal subscribeNext:^(id  _Nullable x) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"加入黑名单成功")] clickHidden:NO clickBlock:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"blackListChange" object:nil];
            }];
            
            [signal subscribeError:^(NSError * _Nullable error) {
//                [MBManager hideAlert];
                [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"加入黑名单失败")] clickHidden:NO clickBlock:nil];
            }];
        }];
    }];
    
    PopoverAction *jubaoAction = [PopoverAction actionWithTitle:ASLocalizedString(@"举报")handler:^(PopoverAction *action) {
        NSString *url = [NSString stringWithFormat:@"%@post/%@/report", KBDBaseURL, @(post.my_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"id":@(post.my_id)};
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"举报成功")] clickHidden:NO clickBlock:nil];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"举报失败")] clickHidden:NO clickBlock:nil];
        }];
    }];
    
    NSString *freezStirng = post.status == BDPostStatusFrozen ? ASLocalizedString(@"解冻"): ASLocalizedString(@"冻结");
    PopoverAction *freezAction = [PopoverAction actionWithTitle:freezStirng handler:^(PopoverAction *action) {
        NSString *url = [NSString stringWithFormat:@"%@post/%@/disable", KBDBaseURL, @(post.my_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"id":@(post.my_id)};
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_DELETE:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), freezStirng] clickHidden:NO clickBlock:nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"deletedPost" object:self.model];
            //这里要删除当前行
            #warning 这里需要处理
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), freezStirng] clickHidden:NO clickBlock:nil];
        }];
    }];
    
    NSString *pingbiString = post.is_public ? ASLocalizedString(@"屏蔽"): ASLocalizedString(@"取消屏蔽");
    PopoverAction *pingbiAction = [PopoverAction actionWithTitle:pingbiString handler:^(PopoverAction *action) {
        NSString *url = [NSString stringWithFormat:@"%@posts/%@/public", KBDBaseURL, @(post.my_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_PUT:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@成功"), pingbiString] clickHidden:NO clickBlock:nil];
            post.is_public = [x[@"is_public"] integerValue];
            //这里还要考虑在屏蔽成功之后的一些操作
            //这里要在当前控制器处理了
            #warning 这里需要处理
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"pingbiAction" object:self.model];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"%@失败"), pingbiString] clickHidden:NO clickBlock:nil];
        }];
    }];
    
    PopoverAction *deletedAction = [PopoverAction actionWithTitle:ASLocalizedString(@"删除")handler:^(PopoverAction *action) {
        NSString *url = [NSString stringWithFormat:@"%@post/%@/disable", KBDBaseURL, @(post.my_id)];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"id":@(post.my_id)};
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        RACSignal *signal = [[BDNetworkingServer yy_DELETE:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"删除成功")] clickHidden:NO clickBlock:nil];
#warning 这里需要处理
            //这个删除要在当前控制器处理
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"deletedPost" object:self.model];
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"blackListChange" object:nil];
            
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:[NSString stringWithFormat:ASLocalizedString(@"删除失败")] clickHidden:NO clickBlock:nil];
        }];
    }];
    
    
    BOOL needAdd = YES;
    
//    NSArray *firends = [BDFMDBTool queryWithClass:[BDFridentInfo class]];
//    for (BDFridentInfo *friend in firends) {
//        if (post.user.user_id == friend.user_id.integerValue) {
//            needAdd = NO;
//            break;
//        }
//    }
    
    NSMutableArray *actionsArray = nil;
    
    BDUserModel *user = [BDUserModel getCurrentUser];
    if (user.user_id == post.user.user_id) {
        actionsArray = @[deletedAction].mutableCopy;
    }else{
        if (needAdd == YES) {
            actionsArray = @[addFriAction].mutableCopy;
        }else{
            actionsArray = [NSMutableArray array];
        }
        [actionsArray addObjectsFromArray:@[QRAction, facetofaceAction, blackListAction, jubaoAction]];
        
        
        if (user.is_admin == YES) {
            [actionsArray addObject:freezAction];
            [actionsArray addObject:pingbiAction];
        }
    }
    PopoverView *popoverView = [PopoverView popoverView];
    [popoverView showToView:cell.postView.menuButton withActions:actionsArray];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
